package com.bwie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.User;
import com.bwie.common.domain.request.LoginReq;
import com.bwie.common.domain.response.LoginResp;
import com.bwie.common.exceptions.LoginExceptions;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import com.bwie.constants.LoginConstants;
import com.bwie.controller.LoginController;
import com.bwie.remote.RemoteSysUser;
import com.bwie.service.LoginService;
import org.apache.el.parser.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @className: LoginServiceImpl
 * @Description: TODO
 * @version: v1.８.0
 * @author: 郑伦
 * @date: 2025/7/31 10:04
 */
@Service
public class LoginServiceImpl implements LoginService {

    //远程调用
    @Autowired
    RemoteSysUser remoteSysUser;
    //redis
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public LoginResp loginUser(LoginReq loginReq) {
        //远程调用获取用户数据
        Result<User> result = remoteSysUser.selectUser(loginReq);
        User data = result.getData();

        //获取用户名和密码
        String username = loginReq.getUsername();
        String password = loginReq.getPassword();

        //用户名密码校验
        if (StringUtils.isBlank(username)){
            throw new LoginExceptions(LoginConstants.USERNAME_IS_NULL);
        }
        if (StringUtils.isBlank(password)){
            throw new LoginExceptions(LoginConstants.PASSWORD_IS_NULL);
        }

        //判断用户是否存在 不存在提示为注册
        if (data == null){
            throw new LoginExceptions(LoginConstants.LOGIN_IS_NULL);
        }

        //生成token
        HashMap<String, Object> map = new HashMap<>();
        String uuid = IdUtil.fastSimpleUUID();
        map.put(TokenConstants.TOKEN,uuid);

        String token = JwtUtils.createToken(map);
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+uuid,token,30, TimeUnit.MINUTES);

        LoginResp loginResp = new LoginResp();
        loginResp.setToken(token);
        return loginResp;
    }
}